package cc.magicjson.easy.batch.template;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL模板处理器
 */
@Slf4j
public class SqlTemplate {
    // 占位符模式：${name} 或 #{name}
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{([^}]+)}|#\\{([^}]+)}");

    private final String template;
    private final Map<String, String> parameters;

    public SqlTemplate(String template) {
        this.template = template;
        this.parameters = new HashMap<>();
    }

    /**
     * 设置参数
     */
    public SqlTemplate set(String name, String value) {
        parameters.put(name, value);
        return this;
    }

    /**
     * 设置多个参数
     */
    public SqlTemplate setAll(Map<String, String> params) {
        parameters.putAll(params);
        return this;
    }

    /**
     * 批量设置表名、列名等
     */
    public SqlTemplate setTableInfo(String table, String[] columns) {
        set("table", table);
        set("columns", String.join(", ", columns));

        // 生成值占位符
        String[] placeholders = new String[columns.length];
        for (int i = 0; i < columns.length; i++) {
            placeholders[i] = "?";
        }
        set("values", String.join(", ", placeholders));

        return this;
    }

    /**
     * 设置更新子句
     */
    public SqlTemplate setUpdateClause(String[] columns) {
        StringBuilder setClause = new StringBuilder();
        for (int i = 0; i < columns.length; i++) {
            if (i > 0) {
                setClause.append(", ");
            }
            setClause.append(columns[i]).append(" = ?");
        }
        set("setClause", setClause.toString());
        return this;
    }

    /**
     * 设置条件子句
     */
    public SqlTemplate setWhereClause(String whereClause) {
        set("whereClause", whereClause);
        return this;
    }

    /**
     * 渲染SQL
     */
    public String render() {
        if (template == null) {
            throw new IllegalStateException("SQL template is null");
        }

        StringBuffer result = new StringBuffer();
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);

        while (matcher.find()) {
            String placeholder = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
            String value = parameters.get(placeholder);

            if (value == null) {
                log.warn("No value provided for placeholder: {}", placeholder);
                // 保持原样
                matcher.appendReplacement(result, matcher.group());
            } else {
                // 替换占位符
                matcher.appendReplacement(result, Matcher.quoteReplacement(value));
            }
        }
        matcher.appendTail(result);

        return result.toString();
    }

    /**
     * 验证所有占位符都已被替换
     */
    public boolean validate() {
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(render());
        if (matcher.find()) {
            log.error("Unresolved placeholder found: {}", matcher.group());
            return false;
        }
        return true;
    }
}
